<template> 
  <div class="app-container">
    <!-- <el-card class="filter-container" shadow="never">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
          <el-button
            style="float: right"
            @click="searchRoleList()"
            type="primary"
            size="small">
            查询结果
          </el-button>
        </div>
        <div style="margin-top: 15px">
          <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
            <el-form-item label="输入搜索：">
              <el-input style="width: 203px" v-model="listQuery.keyword" placeholder="会员名称/关键字"></el-input>
            </el-form-item>
          </el-form>
        </div>
    </el-card> -->
    <el-card
      class="operate-container"
      shadow="never"
    >
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button
        class="btn-add"
        @click="addRole()"
        size="mini"
      >
        添加
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="roleTable"
        :data="list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="listLoading"
        border
      >

        <!-- <el-table-column type="selection" width="60" align="center"></el-table-column> -->
        <!-- <el-table-column label="编号" width="180" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column> -->

        <el-table-column
          label="角色名称"
          align="center"
        >
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>

        <el-table-column
          label="添加时间"
          width="180"
          align="center"
        >
          <template slot-scope="scope">{{scope.row.createTime | formatTime}}</template>
        </el-table-column>

        <!-- <el-table-column label="用户数量" width="180" align="center">
          <template slot-scope="scope">{{scope.row.adminCount}}</template>
        </el-table-column> -->

        <!-- <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleShowStatusChange(scope.$index, scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status">
            </el-switch>
          </template>
        </el-table-column> -->

        <el-table-column
          label="操作"
          width="350"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleChoose(scope.$index, scope.row)"
            >关联权限
            </el-button>
            <el-button
              size="mini"
              @click="handleUpdate(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div class="batch-operate-container">
      <el-select
        size="small"
        v-model="operateType" placeholder="批量操作">
        <el-option
          v-for="item in operates"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchOperate()"
        type="primary"
        size="small">
        确定
      </el-button>
    </div> -->
    <!-- <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :current-page.sync="listQuery.pageNum"
        :total="total">
      </el-pagination>
    </div> -->

    <el-dialog
      title="权限分配"
      :visible.sync="roleShow"
      width="50%"
    >
      <el-form
        ref="adminFrom"
        label-width="100px"
         :model="role"
      >
       <el-form-item label="关联权限：">
          <el-transfer
            style="display: inline-block"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入权限名称"
            v-model="selectSubject"
            :titles="subjectTitles"
            :data="subjectList">
          </el-transfer>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="roleShow = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleuserMessageConfirm"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import { formatDate } from "@/utils/date";
import {treeList} from '@/api/sys/permission'
  import SingleUpload from '@/components/Upload/singleUpload'
import {
  createRole,
  getRole,
  permissionUp,
  updateRole,
  rolePermission
} from "@/api/sys/role";
import {
  fetchList,
  updateShowStatus,
  updateFactoryStatus,
  deleteRole
} from "@/api/sys/role";
const defaultRole={
    name: ''
  };
export default {

  name: "roleList",
  data() {
    return {
      role:Object.assign({}, defaultRole),
      roleShow: false,
      //所有专题列表
      subjectList: [],
      //专题左右标题
      subjectTitles: ["待选择", "已选择"],
      menuIds: null,

      operates: [
        {
          label: "显示",
          value: "showRole"
        },
        {
          label: "隐藏",
          value: "hideRole"
        }
      ],
      operateType: null,
      listQuery: {
        keyword: null,
        pageNum: 1,
        pageSize: 10
      },
      list: null,
      total: null,
      listLoading: true,
      multipleSelection: [],
      role: {}
    };
  },
  created() {
    this.getList();
  },
  filters: {
    formatTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    formatStatus(status) {
      for (let i = 0; i < defaultStatusOptions.length; i++) {
        if (status === defaultStatusOptions[i].value) {
          return defaultStatusOptions[i].label;
        }
      }
    },
    formatReturnAmount(row) {
      return row.productRealPrice * row.productCount;
    }
  },
  computed: {
    //选中的专题
    selectSubject: {
      get: function() {
        let subjects = [];
        console.log(123)
        if (this.menuIds == null || this.menuIds.length <= 0) {
          return subjects;
        }
        for (let i = 0; i < this.menuIds.length; i++) {
          subjects.push(this.menuIds[i].id);
        }
        return subjects;
      },
      set: function(newValue) {
        this.menuIds = [];
        for (let i = 0; i < newValue.length; i++) {
          this.menuIds.push({ id: newValue[i] });
        }
      }
    }
  },
  methods: {
    handleuserMessageConfirm(formName) {
      this.onSubmit(formName)
    },

    onSubmit(formName) {
            this.$confirm('是否提交数据111', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let serviceIds='';
              console.log('this.role.menuIds =',this.menuIds.length )
              // console.log('this.role =',this.role )
              if (this.menuIds.length >= 1) {
                console.log(1)
                for(let i=0;i<this.menuIds.length;i++){
                  serviceIds += this.menuIds[i].id + ',';
                }
                if (serviceIds.endsWith(',')) {
                  serviceIds = serviceIds.substr(0, serviceIds.length - 1)
                }
                this.role.menuIds = serviceIds;
              } else {
                this.role = {}
                console.log(2,this.role)
                this.role.menuIds = null
              }

                permissionUp(this.id, this.role.menuIds).then(response => {
                  // this.$refs[formName].resetFields();
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration:1000
                  });
                  this.roleShow = false
                  // this.$router.back();
                });

            });


      },

    getMenuList() {
      this.subjectList = []
      treeList().then(response => {
        let list = response.data;
        for (let i = 0; i < list.length; i++) {
          this.subjectList.push({
            label: list[i].name,
            key: list[i].id
          });
          if (list[i].children) {
            let ch1 = list[i].children;
            for (let i = 0; i < ch1.length; i++) {
              this.subjectList.push({
                label: "--" + ch1[i].name,
                key: ch1[i].id
              });
              // if(ch1[i].children){
              //   let ch2 = ch1[i].children;
              //   for (let i = 0; i < ch2.length; i++) {
              //     this.subjectList.push({
              //       label: '---'+ch2[i].name,
              //       key: ch2[i].id
              //     });
              //   }
              // }
            }
          }
        }
      });
    },

    filterMethod(query, item) {
      return item.label.indexOf(query) > -1;
    },
    // 关联权限
    handleChoose(index, row) {
      this.menuIds = []
      this.roleShow = true
      this.id = row.id
      this.getMenuList();
        rolePermission(this.id).then(res => {
          let menuIds = []
          res.data.forEach((item)=>{
            if (item) {
              menuIds.push(item)
            }
          })
          this.menuIds = menuIds
        });
        //  console.log('localStorage.getItem("roleDteailEd")',localStorage.getItem("roleDteailEd"))
        this.role = JSON.parse(localStorage.getItem("roleDteailEd"));
        console.log(this.role);
        // getRole(this.$route.query.id).then(response => {
        //   console.log(213213213)
        //   console.log(response)
        //   this.role = response.data;
        // });

    },

    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data;
        this.total = response.data.length;
        // this.totalPage = response.data.pageNum;
        // this.pageSize = response.data.pageSize;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleUpdate(index, row) {
      localStorage.setItem("roleDteailEd", JSON.stringify(row));
      this.$router.push({ path: "/sys/updateRole", query: { id: row.id } });
    },
    handleDelete(index, row) {
      this.$confirm("是否要删除该记录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let parArr = [];
        parArr.push(row.id);
        deleteRole(parArr).then(response => {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1000
          });
          this.getList();
        });
      });
    },
    getProductList(index, row) {
      console.log(index, row);
    },
    getProductCommentList(index, row) {
      console.log(index, row);
    },
    handleFactoryStatusChange(index, row) {
      var data = new URLSearchParams();
      data.append("ids", row.id);
      data.append("factoryStatus", row.factoryStatus);
      updateFactoryStatus(data)
        .then(response => {
          this.$message({
            message: "修改成功",
            type: "success",
            duration: 1000
          });
        })
        .catch(error => {
          if (row.factoryStatus === 0) {
            row.factoryStatus = 1;
          } else {
            row.factoryStatus = 0;
          }
        });
    },
    handleShowStatusChange(index, row) {
      let data = new URLSearchParams();
      data.append("ids", row.id);
      data.append("showStatus", row.showStatus);
      updateShowStatus(data)
        .then(response => {
          this.$message({
            message: "修改成功",
            type: "success",
            duration: 1000
          });
        })
        .catch(error => {
          if (row.showStatus === 0) {
            row.showStatus = 1;
          } else {
            row.showStatus = 0;
          }
        });
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    searchRoleList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleBatchOperate() {
      console.log(this.multipleSelection);
      if (this.multipleSelection < 1) {
        this.$message({
          message: "请选择一条记录",
          type: "warning",
          duration: 1000
        });
        return;
      }
      let showStatus = 0;
      if (this.operateType === "showRole") {
        showStatus = 1;
      } else if (this.operateType === "hideRole") {
        showStatus = 0;
      } else {
        this.$message({
          message: "请选择批量操作类型",
          type: "warning",
          duration: 1000
        });
        return;
      }
      let ids = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        ids.push(this.multipleSelection[i].id);
      }
      let data = new URLSearchParams();
      data.append("ids", ids);
      data.append("showStatus", showStatus);
      updateShowStatus(data).then(response => {
        this.getList();
        this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000
        });
      });
    },
    addRole() {
      this.$router.push({ path: "/sys/addRole" });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>


